import { Context } from 'koa';
import { UserService } from './../../services/user/user';
import * as jwt from 'jsonwebtoken';
import config from '../../config';

export default class UserController{
	/**
	 * 登录
	 */
	static async login(ctx:Context,next:() => Promise<any>){
		const data = ctx.request.body;
		const user = await UserService.findUserOne({email:data.email});
		if(user){
			if(user.password === data.password){
				const token = jwt.sign({email:user.email,id:user.id}, config.secret, {expiresIn: '1h'});
				ctx.result = {success:true,message:'登录成功！', token , loginId:'test@test.com'};
			}else{
				ctx.result = {success:false,message:'登录失败,密码错误！'};
			}
		}else{
			ctx.result = {success:false,message:'登录失败,账号不存在！'};
		}
		ctx.status = 200;
		next();
	}
	/**
	 * 注册
	 */
	static async register(ctx:Context,next:() => Promise<any>){
		
	}
	/**
	 * 获取登录用户信息
	 */
	static async userInfo(ctx:Context,next:() => Promise<any>){
		const user = ctx.state.user;
		const userInfo = {loginId:'test@test.com',ye:1000};
		// const userInfo = await UserService.findUserOne({id:user.id});
		// ctx.result = {success:true,message:'',data:userInfo.toJSON()};
		ctx.result = {success:true,message:'',data:userInfo};
		ctx.status = 200;
		next();
	}
}